package com.yuba.front.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuba.common.core.constant.ActionTypes;
import com.yuba.common.core.domain.model.MessageMeta;
import com.yuba.common.core.exception.front.LikeException;
import com.yuba.common.core.utils.MapstructUtils;
import com.yuba.common.core.utils.SpringUtils;
import com.yuba.common.mybatis.core.page.PageQuery;
import com.yuba.common.mybatis.core.page.TableDataInfo;
import com.yuba.common.satoken.utils.LoginHelper;
import com.yuba.front.domain.LikePosts;
import com.yuba.front.domain.bo.LikePostsBo;
import com.yuba.front.domain.vo.LikePostsVo;
import com.yuba.front.event.MessageHandleEvent;
import com.yuba.front.event.UnMessageHandleEvent;
import com.yuba.front.event.UpdatePostsEvent;
import com.yuba.front.mapper.LikePostsMapper;
import com.yuba.front.service.ILikePostsService;
import com.yuba.front.service.IPostsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class LikePostsServiceImpl extends ServiceImpl<LikePostsMapper, LikePosts> implements ILikePostsService {

    private final LikePostsMapper likePostsMapper;
    private final IPostsService postsService;

    /**
     * 查询文章点赞
     *
     * @param likeId 主键
     * @return 文章点赞
     */
    @Override
    public LikePostsVo queryById(Long likeId){
        LikePosts likePosts = likePostsMapper.selectById(likeId);
        return MapstructUtils.convert(likePosts, LikePostsVo.class);
    }

    /**
     * 分页查询文章点赞列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 文章点赞分页列表
     */
    @Override
    public TableDataInfo<LikePostsVo> queryPageList(LikePostsBo bo, PageQuery pageQuery) {

        List<LikePostsVo> list = baseMapper.selectListVo(bo);
        Page<LikePosts> page = pageQuery.build();

        Page<LikePostsVo> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        if (CollUtil.isEmpty(list)) {
            return TableDataInfo.build(voPage);
        }
        voPage.setRecords(list);
        return TableDataInfo.build(voPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void likePosts(Long postsId, Long userId, Long acceptUserId) {
        LikePosts likePosts = new LikePosts();
        likePosts.setPostId(postsId);
        likePosts.setUserId(userId);
        int insert = likePostsMapper.insert(likePosts);
        if (insert != 1) {
            throw new LikeException("front.like.error");
        }

        if (!userId.equals(acceptUserId)) {
            // 发送点赞帖子消息
            MessageHandleEvent messageEvent = MessageHandleEvent.builder()
                .type(ActionTypes.LIKE)
                .userId(acceptUserId)
                .senderId(userId)
                .senderNickname(LoginHelper.getLoginUser().getNickname())
                .sourceId(postsId)
                .message("点赞了您的帖子")
                .meta(new MessageMeta()
                    .setType(ActionTypes.POSTS)
                    .setPostsId(postsId)
                )
                .build();
            SpringUtils.context().publishEvent(messageEvent);
        }

        // 修改 文章的推荐分
        UpdatePostsEvent event = UpdatePostsEvent.build(postsId, ActionTypes.LIKE, true);
        SpringUtils.context().publishEvent(event);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlikePosts(Long postsId, Long acceptUserId,  Long userId) {
        LambdaQueryWrapper<LikePosts> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LikePosts::getPostId, postsId)
                .eq(LikePosts::getUserId, userId);
        int delete = likePostsMapper.delete(lqw);
        if (delete != 1) {
            throw new LikeException("front.unlike.error");
        }
        // 修改 文章的推荐分
        UpdatePostsEvent event = UpdatePostsEvent.build(postsId, ActionTypes.LIKE, false);
        SpringUtils.context().publishEvent(event);

       if (!userId.equals(acceptUserId)) {
           // 发送取消点赞帖子消息
           UnMessageHandleEvent unMessageHandleEvent = UnMessageHandleEvent.builder()
               .type(ActionTypes.LIKE)
               .userId(acceptUserId)
               .senderId(userId)
               .sourceId(postsId)
               .meta(new MessageMeta()
                   .setType(ActionTypes.POSTS)
                   .setPostsId(postsId))
               .build();

           SpringUtils.context().publishEvent(unMessageHandleEvent);
       }
    }

    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    private LambdaQueryWrapper<LikePosts> buildQueryWrapper(LikePostsBo bo) {
//        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LikePosts> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, LikePosts::getUserId, bo.getUserId());
        lqw.eq(bo.getPostId() != null, LikePosts::getPostId, bo.getPostId());
        return lqw;
    }
}
